package com.github.xuemingyu.springboot.acticitycloud.service.impl;

import com.bidanet.bdcms.core.vo.Page;
import com.bidanet.hibernate.lambda.core.LambdaCriteria;
import com.framework.cache.CacheManager;
import com.github.xuemingyu.springboot.acticitycloud.dao.ActivityDao;
import com.github.xuemingyu.springboot.acticitycloud.dao.RegistrationDao;
import com.github.xuemingyu.springboot.acticitycloud.driver.dingtalk.DingTalkService;
import com.github.xuemingyu.springboot.acticitycloud.entity.Activity;
import com.github.xuemingyu.springboot.acticitycloud.entity.Registration;
import com.github.xuemingyu.springboot.acticitycloud.service.RegistrationService;
import com.google.common.base.Strings;
import com.taobao.api.ApiException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.awt.dnd.DropTargetEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: xmy
 * \* Date: 2019/1/24
 * \* Time: 11:07
 * \
 */
@Service
@Transactional
public class RegistrationServiceImpl extends BaseServiceImpl<Registration> implements RegistrationService {
    @Autowired
    private RegistrationDao registrationDao;
    @Autowired
    private DingTalkService dingTalkService;
    @Autowired
    private ActivityDao activityDao;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    CacheManager cacheManager = CacheManager.getInstance().putListener();

    @Override
    public void queryLike(Registration registration, Page<Registration> page) {
        LambdaCriteria<Registration> lambdaCriteria = lambdaQuery.create(Registration.class);
        if (Objects.nonNull(registration.getActivityId())) {
            lambdaCriteria.eq(q -> {
                q.setActivityId(registration.getActivityId());
            });
        }
        lambdaCriteria.eq(q -> {
            q.setDeleteTag(false);
        });
        List<Registration> list = lambdaCriteria.orderDesc("modelId").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setTotal(count);
        page.setList(list);
    }

    //报名
    @Override
    public void insert(Registration registration) throws ApiException {
        checkNull(registration.getActivityId(), "活动id不能为空");
        checkString(registration.getPerData(), "报名信息不能为空");
        checkString(registration.getUserId(), "userId不能为空");
        String createTime = simpleDateFormat.format(new Date());
        Activity firstByActivityId = activityDao.findFirstByActivityId(registration.getActivityId());
        checkNull(firstByActivityId, "活动不存在");
        Long num = firstByActivityId.getActivityPersMax() - firstByActivityId.getActivityPersnNow();
        Registration firstByActivityIdAndUserId = registrationDao.findFirstByActivityIdAndUserId(registration.getActivityId(), registration.getUserId());
        if (firstByActivityId.getSignStart().compareTo(createTime) > 0) {
            errorMsg("活动报名还没有开始");
        } else if (firstByActivityId.getSignEnd().compareTo(createTime) < 0) {
            errorMsg("活动报名已结束");
        } else if (num <= 0) {
            errorMsg("报名人数已达上限");
        } else if (Objects.nonNull(firstByActivityIdAndUserId)) {
            errorMsg("您已报名过该活动");
        }
        registration.setUserName(dingTalkService.getUserInfoByUserId(registration.getUserId()).getName());
        registration.setCreateTime(createTime);
        registration.setDeleteTag(false);
        registration.setSignTag(false);
        registration.setStatus("已报名");
        registrationDao.save(registration);
        firstByActivityId.setActivityPersnNow(firstByActivityId.getActivityPersnNow() + 1L);
        activityDao.save(firstByActivityId);
    }

    //取消报名
    @Override
    public void joinout(Long activityId, String userId) {
        checkNull(activityId, "活动id不能为空");
        checkString(userId, "userId不能为空");
        List<Registration> status = registrationDao.findAllByActivityIdAndUserIdAndStatus(activityId, userId, "已取消");
        if (Objects.nonNull(status) || status.size() > 0) {
            registrationDao.delete(status);
        }
        String now = simpleDateFormat.format(new Date());
        Activity activity = activityDao.findFirstByActivityId(activityId);
        if (activity.getSignStart().compareTo(now) < 0 || activity.getSignEnd().compareTo(now) > 0) {
            errorMsg("取消报名已结束");
        }
        if (activity.getActivityPersnNow() > 0) {
            activity.setActivityPersnNow(activity.getActivityPersnNow() - 1);
            activityDao.save(activity);
        }
        Registration registration = registrationDao.findFirstByActivityIdAndUserId(activityId, userId);
        registration.setStatus("已取消");
        registrationDao.save(registration);
    }

    //签到
    @Override
    public void update(Registration registration) {
        checkString(registration.getUserId(), "userId不能为空");
        checkString(registration.getSignAddr(), "签到地址不能为空");
        checkNull(registration.getActivityId(), "活动id不能为空");
        String signTime = simpleDateFormat.format(new Date());
        Activity activity = activityDao.findFirstByActivityId(registration.getActivityId());
        checkNull(activity, "活动不存在");
        Registration firstByActivityIdAndUserId = registrationDao.findFirstByActivityIdAndUserId(registration.getActivityId(), registration.getUserId());
        if (Objects.isNull(firstByActivityIdAndUserId)) {
            errorMsg("请先报名");
        } else if (firstByActivityIdAndUserId.isSignTag()) {
            errorMsg("您已签到过了");
        } else if (activity.getActivityStart().compareTo(signTime) > 0) {
            errorMsg("活动未开始");
        } else if (activity.getActivityEnd().compareTo(signTime) < 0) {
            errorMsg("活动已结束");
        }
        firstByActivityIdAndUserId.setSignTag(true);
        firstByActivityIdAndUserId.setSignAddr(registration.getSignAddr());
        firstByActivityIdAndUserId.setSignTime(signTime);
        if (StringUtils.isNotEmpty(registration.getSignFile())) {
            firstByActivityIdAndUserId.setSignFile(registration.getSignFile());
        }
        registrationDao.save(firstByActivityIdAndUserId);
    }

    @Override
    public void delete(Long id) {
        Registration one = registrationDao.findOne(id);
        one.setDeleteTag(true);
        registrationDao.save(one);
    }

    @Override
    protected JpaRepository<Registration, Long> getDao() {
        return registrationDao;
    }
}
